<?php namespace Xcx;

// 网站栏目操作类
class Category extends \Xcx\Member
{

    public $space; // 网站的
    public $category; // 网站的栏目信息
    public $mymodule; // 可用的内容模块信息

    public function __construct(...$params) {
        parent::__construct(...$params);
        // 初始化数据表
        $this->is_data = 0;
        $this->tpl_name = 'category';
        $this->_init([
            'xid' => $this->xcx['id'],
            'table' => 'xcx_category',
            'field' => [
                'thumb' => [
                    'name' => dr_lang('缩略图'),
                    'ismain' => 1,
                    'ismember' => 1,
                    'fieldtype' => 'File',
                    'fieldname' => 'thumb',
                    'setting' => array(
                        'option' => array(
                            'ext' => 'jpg,gif,png,jpeg',
                            'size' => 1,
                            'input' => 1,
                            'attachment' => defined('SYS_FIELD_THUMB_ATTACH') ? SYS_FIELD_THUMB_ATTACH : 0,
                        )
                    )
                ],

            ],
            'order_by' => 'displayorder ASC,id ASC',
            'where_list' => 'xid='.XCX_ID,
        ]);

        \Phpcmf\Service::M('category', 'xcx')->init($this->init); // 初始化内容模型


        $this->mymodule = $this->_get_mymodule();

        \Phpcmf\Service::V()->assign([
            'mymodule' => $this->mymodule ,
        ]);
    }

    // ========================

    // 获取树形结构列表
    protected function _get_tree_list($data) {

        $tree = [];
        foreach($data as $t) {
            $t['name'] = dr_strcut($t['name'], 30);
            $t['child'] = $t['pcatpost'] ? 0 : $t['child'];
            $t['setting'] = dr_string2array($t['setting']);
            $option = '';

            $t['tid'] != 2 && $option.= '<a class="btn btn-xs blue" href='.dr_xcx_url('category/add', array('pid' => $t['id'])).'> <i class="fa fa-plus"></i> '.dr_lang('子类').'</a>';
            $option.= '<a class="btn btn-xs green" href='.dr_xcx_url('category/edit', array('id' => $t['id'])).'> <i class="fa fa-edit"></i> '.dr_lang('修改').'</a>';
            ($t['tid'] == 1 && !$t['child']) && $option.= '<a class="btn btn-xs dark" href='.dr_xcx_url($t['mid'].'/add', array('catid' => $t['id'])).'> <i class="fa fa-plus"></i> '.dr_lang('发布').'</a>';

            // 判断显示和隐藏开关
            $t['is_show_html'] = '<a href="javascript:;" onclick="dr_cat_ajax_show_open_close(this, \''.dr_xcx_url('category/show_edit', ['id'=>$t['id']]).'\', 0);" class="badge badge-'.(!$t['show'] ? 'no' : 'yes').'"><i class="fa fa-'.(!$t['show'] ? 'times' : 'check').'"></i></a>';

            $t['mid'] && $t['mid'] = $this->mymodule[$t['mid']]['name'];


            // 栏目类型
            $t['type_html'] = '<span class="badge badge-info"> '.dr_lang('单页').' </span>';
            if ($t['tid'] == 1) {
                $t['type_html'] = '<span class="badge badge-success"> '.dr_lang('模块').' </span>';
            }
            !$t['mid'] && $t['mid'] = '<span class="label label-sm label-danger circle">'.dr_lang('无').'</span>';
            $t['option'] = $option;
            $tree[$t['id']] = $t;
        }


        $str = "<tr class='\$class'>";
        $str.= "<td class='myselect'>
                    <label class='mt-table mt-table mt-checkbox mt-checkbox-single mt-checkbox-outline'>
                        <input type='checkbox' class='checkboxes' name='ids[]' value='\$id' />
                        <span></span>
                    </label>
                </td>";
        $str.= "<td style='text-align:center'> <input type='text' onblur='dr_cat_ajax_save(this.value, \$id)' value='\$displayorder' class='displayorder form-control input-sm input-inline input-mini'> </td>";
        $str.= "<td style='text-align:center'>\$is_show_html</td>";
        $str.= "<td>\$spacer \$name \$parent</td>";
        $str.= "<td style='text-align:center'>\$mid</td>";
        $str.= "<td>\$option</td>";
        $str.= "</tr>";


        return \Phpcmf\Service::L('Tree')->init($tree)->html_icon()->get_tree(0, $str);
    }

    // 查看列表
    public function index() {

        list($tpl, $data) = $this->_List([], -1);

        $category = \Phpcmf\Service::M('category', 'xcx')->repair($data['list']);

        \Phpcmf\Service::V()->assign([
            'list' => $this->_get_tree_list($category),
            'move_select' => \Phpcmf\Service::L('Tree')->select_category(
                $category,
                0,
                'name="catid"',
                '--',
                0, 0
            ),
        ]);
        \Phpcmf\Service::V()->display($tpl);
    }

    // 添加内容
    public function add() {

        $id = 0;
        $pid = intval(\Phpcmf\Service::L('input')->get('pid'));
        $page = intval(\Phpcmf\Service::L('input')->get('page'));

        // 默认数据
        $value = [
            'show' => 1,
        ];

        $this->category = \Phpcmf\Service::M('category', 'xcx')->get_category();

        $pid && !$this->category[$pid] && $this->_msg(0, dr_lang('栏目【%s】不存在', $pid));
        $value['mid'] = $this->category[$pid]['mid'];

        list($tpl) = $this->_Post($id, $value, 1);

        \Phpcmf\Service::V()->assign([
            'form' =>  dr_form_hidden(['page' => $page]),
            'mypage' => $page,
            'select' => \Phpcmf\Service::L('Tree')->select_category($this->category, $pid, 'name=\'data[pid]\'', dr_lang('顶级栏目')),
            'is_edit_mid' => $pid && $value['mid'] ? 1 : 0,
        ]);
        \Phpcmf\Service::V()->display($tpl);
    }

    // 修改内容
    public function edit() {

        $id = intval(\Phpcmf\Service::L('input')->get('id'));
        $page = intval(\Phpcmf\Service::L('input')->get('page'));

        $this->category = \Phpcmf\Service::M('category', 'xcx')->get_category();

        list($tpl, $data) = $this->_Post($id, null, 1);
        !$data['data'] && $this->_msg(0, dr_lang('栏目数据#%s不存在', $id));

        \Phpcmf\Service::V()->assign([
            'mypage' => $page,
            'form' =>  dr_form_hidden(['page' => $page]),
            'select' => \Phpcmf\Service::L('Tree')->select_category($this->category, $data['data']['pid'], 'name=\'data[pid]\'', dr_lang('顶级栏目')),
            'is_edit_mid' => 1,
        ]);
        \Phpcmf\Service::V()->display($tpl);
    }

    // 批量添加
    public function all_add() {

        $this->category = \Phpcmf\Service::M('category', 'xcx')->get_category();

        if (IS_AJAX_POST) {

            $post = \Phpcmf\Service::L('input')->post('data');
            $list = explode(PHP_EOL, $post['list']);
            !$list && $this->_json(0, dr_lang('内容填写不完整'));

            $pid = intval($post['pid']);
            $pid && !$this->category[$pid] && $this->_json(0, dr_lang('栏目【%s】缓存不存在', $pid));

            $count = 0;

            foreach ($list as $t) {
                list($name, $dir) = explode('|', $t);
                $data = [];
                $data['name'] = trim($name);
                if (!$data['name']) {
                    continue;
                }
                $data['dirname'] = trim($dir);
                !$data['dirname'] && $data['dirname'] = \Phpcmf\Service::L('pinyin')->result($data['name']);
                \Phpcmf\Service::M('category', 'xcx')->check_dirname(0, $data['dirname']) && $data['dirname'].= rand(0,99);
                $data['pid'] = $pid;
                $data['show'] = 1;
                $data['thumb'] = '';
                $data['pids'] = '';
                $data['pdirname'] = '';
                $data['childids'] = '';
                $data['content'] = '';
                //$data['tid'] = (int)$post['tid'];
                $data['tid'] = 1;
                $data['mid'] = $post['mid'];
                $data['xid'] = $this->xcx['id'];

                // 作为内容模块的栏目判断
                if ($data['tid'] == 1) {
                    !$data['mid'] && $this->_json(0, dr_lang('必须选择一个模块'));
                    // 判断逐个父级栏目的mid值
                    list($pmid, $ids) = \Phpcmf\Service::M('category', 'xcx')->get_parent_mid($this->category, $pid);
                    $pmid && $pmid != $data['mid'] && $this->_json(0, dr_lang('必须选择与上级栏目相同的内容模块（%s）', $pmid));
                }
                $data['setting'] = dr_array2string([
                    'edit' => 1,
                ]);
                $rt = \Phpcmf\Service::M('category', 'xcx')->insert($data);
                !$rt['code'] && $this->_json(0, $rt['msg']);
                $count ++;
            }
            $this->_json(1, dr_lang('批量添加%s个栏目', $count));
            exit;
        }

        \Phpcmf\Service::V()->assign([
            'form' =>  dr_form_hidden(),
            'select' => \Phpcmf\Service::L('Tree')->select_category($this->category, 0, 'name=\'data[pid]\'', dr_lang('顶级栏目')),

        ]);
        \Phpcmf\Service::V()->display('category_all.html');
    }



    // 删除内容
    public function del() {

        $ids = \Phpcmf\Service::L('input')->get_post_ids();
        !$ids && $this->_json(0, dr_lang('所选栏目不存在'));

        // 重新获取数据
        $category = \Phpcmf\Service::M('category', 'xcx')->data_for_delete();

        // 筛选栏目id
        $catid = '';
        foreach ($ids as $id) {
            $catid.= ','.($category[$id]['childids'] ? $category[$id]['childids'] : $id);
        }

        $catid = explode(',', trim($catid, ','));
        $catid = array_flip(array_flip($catid));

        parent::_Del(
            $catid,
            null,
            function ($rows) {
                // 删除之后记得删除相关模块数据
                foreach ($rows as $t) {
                }
                // 删除对应的栏目模型字段
                return dr_return_data(1);
            },
            \Phpcmf\Service::M()->dbprefix($this->init['table'])
        );
    }


    // 后台批量保存排序值
    public function displayorder_edit() {
        $this->_Display_Order(
            intval(\Phpcmf\Service::L('input')->get('id')),
            intval(\Phpcmf\Service::L('input')->get('value'))
        );
    }

    // 后台批量移动栏目
    public function move_edit() {

        $ids = \Phpcmf\Service::L('input')->get_post_ids();
        !$ids && $this->_json(0, dr_lang('所选栏目不存在'));

        // 重新获取数据
        $category = \Phpcmf\Service::M('category', 'xcx')->data_for_move();

        $cid = (int)\Phpcmf\Service::L('input')->post('catid');
        !$category[$cid] && $this->_json(0, dr_lang('所选移动栏目不存在'));

        $mid = $category[$cid]['mid'];

        $catid = [];
        foreach ($ids as $id) {
            $catid = dr_array2array($catid, explode(',', $category[$id]['childids']));
        }

        // 判断mid
        $mmid = '';
        foreach ($catid as $id) {
            if ($mid) {
                // 本身有模块属性的栏目
                if ($category[$id]['mid'] && $category[$id]['mid'] != $mid) {
                    $this->_json(0, dr_lang('所选栏目【%s】与目标栏目的模块不一致', $category[$id]['name']));
                }
            } else {
                // 本身没有模块属性的栏目
                !$mmid && $category[$id]['mid'] && $mmid = $category[$id]['mid'];
                if ($category[$id]['mid'] && $category[$id]['mid'] != $mmid) {
                    $this->_json(0, dr_lang('所选栏目【%s】与其他栏目的模块不一致', $category[$id]['name']));
                }
            }
            // 批量更新内容栏目
            //$this->content_model->my_update_catid($id, $cid);
        }

        // 批量更换栏目
        \Phpcmf\Service::M()->db->table($this->init['table'])->whereIn('id', $catid)->update(['pid' => $cid]);


        $this->_json(1, dr_lang('操作成功'));
    }

    // 后台批量保存显示状态
    public function show_edit() {

        $id = (int)\Phpcmf\Service::L('input')->get('id');
        $row = \Phpcmf\Service::M('category', 'xcx')->init($this->init)->get($id);
        !$row && $this->_json(0, dr_lang('栏目数据不存在'));

        $v = $row['show'] ? 0 : 1;
        \Phpcmf\Service::M('category', 'xcx')->init($this->init)->update($id, ['show' => $v]);

        exit($this->_json(1, dr_lang($v ? '显示状态' : '隐藏状态'), ['value' => $v, 'share' => 0]));
    }





    // ===========================

    /**
     * 获取内容
     * $id      内容id,新增为0
     * */
    protected function _Data($id = 0) {

        $row = \Phpcmf\Service::M('category', 'xcx')->get($id);
        if (!$row) {
            return [];
        }

        $row['setting'] = dr_string2array($row['setting']);

        return $row;
    }

    /**
     * 保存内容
     * $id      内容id,新增为0
     * $data    提交内容数组,留空为自动获取
     * $func    格式化提交的数据
     * */
    protected function _Save($id = 0, $data = [], $old = [], $func = null, $func2 = null) {

        return parent::_Save($id, $data, $old,
            function ($id, $data, $old){
                // 保存之前的判断
                $save = \Phpcmf\Service::L('input')->post('data');
                if (!$save['name']) {
                    return dr_return_data(0, dr_lang('栏目名称不能为空'), ['field' => 'name']);
                }
                /*
                elseif (!$save['dirname']) {
                    return dr_return_data(0, dr_lang('目录名称不能为空'), ['field' => 'dirname']);
                } elseif (\Phpcmf\Service::M('category', 'xcx')->check_dirname($id, $save['dirname'])) {
                    return dr_return_data(0, dr_lang('目录名称不可用'), ['field' => 'dirname']);
                }*/

                // 默认数据
                $save['show'] = (int)$save['show'];
                foreach ($data[1] as $n => $t) {
                    $save[$n] = $t ? $t : '';
                }

                $save['tid'] = 1;

                // 判断模块tid是否正确
                if (isset($save['tid'])) {
                    $save['tid'] = intval($save['tid']);
                    if ($save['tid'] == 1 && !$save['mid']) {
                        return dr_return_data(0, dr_lang('必须选择一个模块'));
                    } elseif ($save['pid'] && $save['tid'] != 2 && $this->category[$save['pid']]['tid'] == 2) {
                        //return dr_return_data(0, dr_lang('父级栏目是外部地址类型，下级栏目只能选择外部地址'));
                    } elseif ($save['tid'] == 2 && !$save['setting']['linkurl']) {
                        //return dr_return_data(0, dr_lang('外部地址类型必须填写地址'));
                    }
                    // 单页模板识别
                    //!$save['tid'] && $save['setting']['template']['list'] == 'list.html' && $save['setting']['template']['list'] = 'page.html';
                }

                $save['xid'] =  $this->xcx['id'];

                if ($save['pid'] && $id && $save['pid'] == $id) {
                    return dr_return_data(0, dr_lang('栏目上级不能为本身'));
                }

                if ($id) {
                    // 表示修改栏目
                    if ($save['tid'] != $old['tid']) {
                        return dr_return_data(0, dr_lang('栏目类型不允许修改'));
                    } elseif ($save['mid'] && $save['mid'] != $old['mid']) {
                        return dr_return_data(0, dr_lang('内容模块不允许修改'));
                    }
                }

                // 数组json化
                $save['setting'] = dr_array2string($save['setting']);
                $save['pids'] = '';
                $save['pdirname'] = '';
                $save['childids'] = '';

                return dr_return_data(1, '', [1 => $save]);
            }, function ($id, $data, $old) {

            }
        );
    }
}
